import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import iView from 'iview'
import { getToken, getHomeRouteByRole } from '@/libs/util'
import { getPermission } from '@/libs/permission'
import store from '@/store'

Vue.use(Router)

function initHomeRoute () {
    if (!getToken()) return
    const role = store.state.user.roleType
    const permission = getPermission(role)
    store.commit('setHomeRoute', getHomeRouteByRole(permission, routes))
}
initHomeRoute()

const router = new Router({
    routes,
    mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
    // 登录加载在登录页面控制
    if (from.path !== '/login') {
        iView.LoadingBar.start()
    }
    const token = getToken()
    // 是否登录判断
    if (token) {
        // 已登录去登录页则跳转首页
        if (to.name === LOGIN_PAGE_NAME) {
            next({ name: store.state.app.homeRoute.name })
            return
        }
        next()
    } else {
        // 如果是白名单页面则直接跳转 否则去登录
        to.meta.wt
            ? next()
            : next({ name: LOGIN_PAGE_NAME })
    }
})

router.afterEach(to => {
    iView.LoadingBar.finish()
    window.scrollTo(0, 0)
})

export default router
